package com.itheima.controller;

import com.gargoylesoftware.htmlunit.HttpMethod;
import com.itheima.config.ThreadPoolConfig;
import com.itheima.myenum.SpiderStatus;
import com.itheima.spider.BilibiliSpider;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.DragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;

import javafx.scene.text.Text;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import javax.swing.plaf.SpinnerUI;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

public class MainFxml {
    @FXML
    public TextField inputText;
    @FXML
    public Button DownloadBu;


    // 默认保存路径 格式 D:\我的音乐\周杰伦
    public String  savePath = "D:\\";;
    @FXML
    public Text downLoadStatus;
    @FXML
    public Label player;
    @FXML
    public CheckBox onlyForAu;

    public Boolean isOnlyForAu = false;



    @FXML
    public Spinner<Integer> numberOfChapters;
    @FXML
    public ImageView imageBu;

    @FXML //fxml中绑定的方法
    public void Download(MouseEvent mouseEvent) throws IOException {
        numberOfChapters.setDisable(true); //禁用 Spinner
        SelectSavePath();
        String url = inputText.getText();
        //判断是不是 有效的URL地址 https://www.bilibili.com/video/BV1H7z3YBE42?t=1.3&p=78
        if (!url.matches("https?://.+")) {
            downLoadStatus.setText("Invalid URL");
            return;
        }
        if (url.isEmpty()) {
            return;
        }
        if (numberOfChapters.getValue()==1){
            submitTask(url);
        }else {
            //https://www.bilibili.com/video/BV1H7z3YBE42?t=1.3&p=78
            String[] split = url.split("\\?");
            String newUrl = split[0]; //去掉后面的参数 比如 t=1.3&p=78
            System.out.println("newurl：" + newUrl); //https://www.bilibili.com/video/BV1H7z3YBE42
            String[] split1 = url.split("="); //从提交的url这一集开始
            if(split1.length>=2){
               //倒数第二个不包含p，不能批量爬取
               if (!split1[split1.length - 2].matches(".*p.*")) {
                   System.out.println(Arrays.toString(split1));
                   System.out.println("没有附带p参数，无法批量爬取");
//                   submitTask(url);
               }else {
                   try {
                       //默认 p值一直在参数最后面
                       int startChapter = Integer.parseInt(split1[split1.length - 1]);
                       System.out.println("startChapter is "+ startChapter);
                       // 随机构造t，在0.5到1.5之间随机一个数 比如 1.2 只要一位小数

                       for (int i = 0; i < numberOfChapters.getValue(); i++) {
                           //打乱t数组获取第一个
                           String nurl=newUrl + "?t="+0.1+"&p=" + (startChapter + i);
                           System.out.println(nurl);
                           submitTask(nurl);
                       }
                   }catch (Exception e){
                       e.getCause();
                       System.out.println("参数解析异常");
                   }
               }
             }
        }

    }
    private void submitTask(String url) throws IOException {
        ThreadPoolConfig.getThreadPool().submit(() -> {
           if (numberOfChapters.getValue()==1) {
               downLoadStatus.setText("Downloading...");
           }
           if (numberOfChapters.getValue()>1){
               downLoadStatus.setText("Wait a moment, this will take some time");
           }
            BilibiliSpider bilibiliSpider = null;
            try {
                bilibiliSpider = new BilibiliSpider(new URL(url), HttpMethod.GET);
                if (isOnlyForAu&& Objects.equals(bilibiliSpider.spiderStatus, SpiderStatus.SUCCESS.getCode())) {
                    bilibiliSpider.onlyForAu(savePath);
                } else if (!isOnlyForAu && Objects.equals(bilibiliSpider.spiderStatus, SpiderStatus.SUCCESS.getCode())) {
                    bilibiliSpider.Download_Merge_VideoAndAudio(savePath);
                }
                // 关闭浏览器
                bilibiliSpider.webClient.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (numberOfChapters.getValue()==1){
                Integer finalBilibiliSpider = bilibiliSpider.spiderStatus;
                Platform.runLater(() -> { //告诉主线程我们要更新ui
                    if (Objects.equals(finalBilibiliSpider, SpiderStatus.SUCCESS.getCode())){
                        downLoadStatus.setText("Downloaded Successfully");
                        numberOfChapters.setDisable(false); //启用 Spinner
                    }
                    if (Objects.equals(finalBilibiliSpider, SpiderStatus.REJECTED.getCode())){
                        downLoadStatus.setText("Rejected");
                        numberOfChapters.setDisable(false); //启用 Spinner
                    }
                    if (Objects.equals(finalBilibiliSpider, SpiderStatus.NO_MATCH.getCode())){
                        downLoadStatus.setText("No Match");
                        numberOfChapters.setDisable(false); //启用 Spinner
                    }
                });
            }else if (numberOfChapters.getValue()>1){
                // 线程池没有任务在执行了 就更新ui 否则不更新
               if (ThreadPoolConfig.getThreadPool().getActiveCount()==0){
                   Platform.runLater(()->{
                        downLoadStatus.setText("Batch download completed");
                        numberOfChapters.setDisable(false); //启用 Spinner
                   });
               }
            }
        });
    }

    public void SelectSavePath() {
        if (numberOfChapters.getValue()==1){
            System.out.println("chapter number is "+numberOfChapters.getValue());
            FileChooser fileChooser = new FileChooser(); //创建文件选择器
            fileChooser.setTitle("选择保存路径");
            // 设置文件过滤器，只允许选择
            fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("mp4", "*.mp4"),new FileChooser.ExtensionFilter("mp3", "*.mp3"));
            // 显示保存对话框，并获取选择的文件路径
            File file = fileChooser.showSaveDialog(DownloadBu.getScene().getWindow());
            if (file != null) {
                savePath = file.getPath();
//            System.out.println(savePath);
            }
        }
        if (numberOfChapters.getValue()>1) {
            System.out.println("chapter number is "+numberOfChapters.getValue());
            // 创建目录选择器
            DirectoryChooser directoryChooser = new DirectoryChooser();
            directoryChooser.setTitle("选择保存路径");
            File directory = directoryChooser.showDialog(DownloadBu.getScene().getWindow());
            if (directory != null) {
                savePath = directory.getPath();
                System.out.println("保存目录：：："+savePath);
            }

        }

    }

    public void playVideo(DragEvent dragEvent) {
        if (dragEvent.getDragboard().hasFiles()){
            File file = dragEvent.getDragboard().getFiles().get(0);
            String url = file.toURI().toString();
            Platform.runLater(() -> {
                try {
                    scene2Play(url);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    //这个函数创建一个新的 窗口来播放视频
   private void scene2Play(String url) throws IOException {

        FXMLLoader fxmlLoader = new FXMLLoader();
        // 设置加载的fxml文件的位置
        fxmlLoader.setLocation(Objects.requireNonNull(getClass().getResource("/mediaViewFx.fxml")));
        Parent load = fxmlLoader.load();
        MediaViewFx controller = fxmlLoader.getController();

        controller.setMediaPlayer(url);

        Scene scene = new Scene(load);

        Stage stage = new Stage();
        stage.setScene(scene);
        stage.setTitle("play video");
        //设置图标
        stage.getIcons().add(new Image("/image/img.png"));
        //窗口最大化
       controller.getMediaView().setPreserveRatio(true); //保持比例
       controller.getMediaView().fitHeightProperty().bind(stage.heightProperty());
       controller.getMediaView().fitWidthProperty().bind(stage.widthProperty());
        stage.setOnCloseRequest(event -> {
            controller.getMediaView().getMediaPlayer().stop();
        });
        stage.show();


    }

    public void initialize() {
        // 初始化时设置 CheckBox 的监听器
        onlyForAu.setOnAction(event -> {
            // CheckBox 状态变化
            if (onlyForAu.isSelected()) {
                System.out.println("CheckBox 选中");
                isOnlyForAu = true;
            } else {
                System.out.println("CheckBox 未选中");
                isOnlyForAu = false;
            }
        });


        // 设置范围，最小值，最大值，增量值
      numberOfChapters.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(1, 100, 1));
//
//        numberOfChapters.valueProperty().addListener((observable, oldValue, newValue) -> {
////            System.out.println("当前章节数：" + newValue);
//        });
//        numberOfChapters.getEditor().textProperty().addListener((observable, oldValue, newValue) -> {
////            System.out.println("Text changed to: " + newValue);
//        });

    }
    @FXML
    public void dragOver(DragEvent dragEvent) {
        dragEvent.acceptTransferModes(TransferMode.ANY);
    }
}
